package com.taxi.management.config;

import com.taxi.management.entity.UserEntity;
import com.taxi.management.login.UserUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component // 注入Spring
public class WebInterceptor implements HandlerInterceptor {
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 访问controller之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置跨域请求头
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        // 处理 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }

//        String token = request.getHeader("token");
//        if (token == null) {
//            sendErrorResponse(response, -9999, "未传入Token！");
//            return false;
//        }
//
//        UserEntity loginUser = UserUtils.get(token);
//        if (loginUser == null) {
//            sendErrorResponse(response, -9999, "Token错误！");
//            return false;
//        }
//
//        // 只有 id == 1 的用户可以访问受保护资源
//        if (loginUser.getId() != 1) {
//            sendErrorResponse(response, -9999, "权限不足！");
//            return false;
//        }

        return true;
    }

    // 访问controller之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("拦截器postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求处理完成后
        System.out.println("拦截器afterCompletion");
    }

    private void sendErrorResponse(HttpServletResponse response, int code, String msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("code", code);
        errorMap.put("msg", msg);
        String json = objectMapper.writeValueAsString(errorMap);
        response.getWriter().write(json);
    }
}